<?php
/*
 * This file is part of the "nimo-l4" package.
 *
 * (c) Duurenbayar Munkhbayar <duuree69@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace nimo\domains\car_balance\controllers;

use App;
use BaseController;
use Redirect;
use Response;
use Request;
use Sentry;
use Session;
use Route;
use View;
use Input;
use nimo\domains\car_balance\Model\CarMaker;
use nimo\domains\car_balance\Model\PurchaseCar;
use nimo\domains\car_balance\Model\ServiceCompany;
use nimo\domains\car_balance\Model\Customer;
use nimo\domains\car_balance\Model\CarAuction;
use nimo\domains\car_balance\Model\Bill;
use nimo\domains\car_balance\Model\Penalty;

class BillController extends BaseController
{
    public function getIndex()
    {
        // only admin & customer (hyazgaarlagdmal erhteiger) handana
        $this->checkPermission(array('admin', 'customer'));

        // Grab all the containers
        $query = new Bill();

        $query = $query->orderBy('create_date', 'desc');
        $query = $query->orderBy('expiry_date', 'desc');

        if($filter_create_date = e(Request::get('create_date'))) {
            $filter_create_date = is_null(Input::get('create_date')) ? array() : explode(' - ',Input::get('create_date'));
            $query = $query->whereBetween('create_date', array(date('Y-m-d', strtotime($filter_create_date[0])),date('Y-m-d', strtotime($filter_create_date[1]))));
        }

        // only for customer
        if(Sentry::getUser()->hasAccess('customer', false)) {
            // user table-s customer-g herhen tanih we?
            $user = Sentry::getUser();
            $customerQuery = new Customer();
            $customer = $customerQuery->where('id', '=', $user->customer_id)->first();
            if($customer) {
                $filter_customer_id = $customer->id;
            } else {
                App::abort(403, 'Хандах эрх хүрэлцэхгүй байна!');
            }
        }

        if(isset($filter_customer_id) || $filter_customer_id = e(Request::get('customer_id'))) {
            $query = $query->where('customer_id', '=', $filter_customer_id);
        }

        $perpage = Request::has('perpage') ? Request::get('perpage') : 30;
        $page = Request::has('page') ? Request::get('page') : 1;
        $total_page = ($query->count() / $perpage) + (($query->count() % $perpage > 0)? 1: 0);
        $pagination = array('total_page' => $total_page, 'perpage' => $perpage, 'page' => $page);

        // Paginate the containers
        $bills = $query->paginate($perpage);

        // Show the page
        return View::make('nimo.domains.car_balance.Main.bill_list', compact('bills', 'pagination', 'filter_create_date', 'filter_customer_id'))
            ->with('customer_list', isset($customer) ? array($customer->id => $customer->name) : array_merge(array('0' => 'All Customer'), Customer::lists('name', 'id')))
            ->with('customer', isset($customer) ? $customer : null)
            ;
    }

    /**
     * PurchaseCar create step1.
     *
     * @return View
     */
    public function getCreateStep1()
    {
        // only admin & customer (hyazgaarlagdmal erhteiger) handana
        $this->checkPermission(array('admin'));

        $query = new PurchaseCar();
        $penalty1 = new Penalty();
        $penalty2 = new Penalty();

        if(Request::has('reset')) {
            Session::forget('bill_car_list.filter');
        }

        if(Request::isMethod('POST')) {
            // Filter form values to session
            $chassis_no = is_null(Input::get('chassis_no')) ? '0' : Input::get('chassis_no');
            Session::put('bill_car_list.filter.chassis_no', $chassis_no);
            $purchase_date = is_null(Input::get('purchase_date')) ? array() : explode(' - ',Input::get('purchase_date'));
            Session::put('bill_car_list.filter.purchase_date', $purchase_date);
            $customer_id = is_null(Input::get('customer_id')) ? '0' : Input::get('customer_id');
            Session::put('bill_car_list.filter.customer_id', $customer_id);
        } else {
            // Filter values from session
            $chassis_no = Session::get('bill_car_list.filter.chassis_no', '0');
            $purchase_date = Session::get('bill_car_list.filter.purchase_date', array());
            $customer_id = Session::get('bill_car_list.filter.customer_id', '0');
        }

        $query = $query->whereNull('bill_id');
        // Applying filters
        if($chassis_no != '0')
            $query = $query->where('chasis_no', 'like', "%$chassis_no");
        if(count($purchase_date) >1 )
            $query = $query->whereBetween('purchase_date', array(date('Y-m-d', strtotime($purchase_date[0])),date('Y-m-d', strtotime($purchase_date[1]))));
        if($customer_id != '0')
            $query = $query->where('customer_id', '=', $customer_id);
        // QUERY ORDER
        $query = $query->orderBy('purchase_date', 'asc');

        $cars = $query->with('customer')->get();

        $penalty1 = $penalty1->whereNull('bill_id');
        // Applying filters
        if($chassis_no != '0')
            $penalty1 = $penalty1->where('chasis_no', 'like', "%$chassis_no");
        if(count($purchase_date) >1 )
            $penalty1 = $penalty1->whereBetween('penalty_date', array(date('Y-m-d', strtotime($purchase_date[0])),date('Y-m-d', strtotime($purchase_date[1]))));
        if($customer_id != '0')
            $penalty1 = $penalty1->where('customer_id', '=', $customer_id);
        // QUERY ORDER
        $penalty1 = $penalty1->orderBy('penalty_date', 'asc');

        $penalties1 = $penalty1->where('penalty_type', '=', '1')->with('customer')->get();

        $penalty2 = $penalty2->whereNull('bill_id');
        // Applying filters
        if($chassis_no != '0')
            $penalty2 = $penalty2->where('chasis_no', 'like', "%$chassis_no");
        if(count($purchase_date) >1 )
            $penalty2 = $penalty2->whereBetween('penalty_date', array(date('Y-m-d', strtotime($purchase_date[0])),date('Y-m-d', strtotime($purchase_date[1]))));
        if($customer_id != '0')
            $penalty2 = $penalty2->where('customer_id', '=', $customer_id);
        // QUERY ORDER
        $penalty2 = $penalty2->orderBy('penalty_date', 'asc');

        $penalties2 = $penalty2->where('penalty_type', '=', '2')->with('customer')->get();

        $filters = array(
            'chassis_no' => $chassis_no,
            'purchase_date' => $purchase_date,
            'customer_id' => $customer_id,
        );

        return View::make('nimo.domains.car_balance.Main.bill_create_step1')
            ->with('cars', $cars)
            ->with('penalties1', $penalties1)
            ->with('penalties2', $penalties2)
            ->with('filters', $filters)
            ->with('customer_list', array_merge(array('0' => 'All Customer'), Customer::lists('name', 'id')))
            ;
    }

    /**
     * PurchaseCar create step1.
     *
     * @return View
     */
    public function getCreateStep()
    {
        // only admin & customer (hyazgaarlagdmal erhteiger) handana
        $this->checkPermission(array('admin'));

        $customer = Request::get('customer');
        $cars = Request::get('cars');
        $penalties1 = Request::get('penalties1');
        $penalties2 = Request::get('penalties2');

        $step1_data = array(
            'customer_id' => $customer,
            'cars'        => $cars,
            'penalties1'   => $penalties1,
            'penalties2'   => $penalties2,
        );
        Session::set('bill_create_step1', $step1_data);
        return Response::json(array('status' => 'ok'));
    }


    /**
     * PurchaseCar create.
     *
     * @return View
     */
    public function getCreate()
    {
        // only admin & customer (hyazgaarlagdmal erhteiger) handana
        $this->checkPermission(array('admin'));

        $step1_data = Session::get('bill_create_step1');

        $query = new PurchaseCar();
        if(count($step1_data['cars']) != 0) {
            $query = $query->whereIn('id', $step1_data['cars']);
            $query = $query->orderBy('purchase_date', 'asc');
        }
        else {
            $query = $query->where('id', '=', '');
        }
        $cars = $query->get();

        $query1 = new Penalty();
        $query1 = $query1->where('customer_id', '=', $step1_data['customer_id']);

        if(count($step1_data['penalties1']) != 0) {
            $query1 = $query1->whereIn('id', $step1_data['penalties1']);
            $query1 = $query1->orderBy('penalty_date', 'asc');
        }
        else {
            $query1 = $query1->where('id', '=', '');
        }
        $penalties1 = $query1->get();

        $query2 = new Penalty();
        $query2 = $query2->where('customer_id', '=', $step1_data['customer_id']);
        if(count($step1_data['penalties2']) != 0) {
            $query2 = $query2->whereIn('id', $step1_data['penalties2']);
            $query2 = $query2->orderBy('penalty_date', 'asc');
        }
        else {
            $query2 = $query2->where('id', '=', '');
        }
        $penalties2 = $query2->get();

        $total_bill = array();
        $total_bill['bill_total_amount'] = 0;
        $total_bill['bill_price'] = 0;
        $total_bill['bill_vat'] = 0;
        $total_bill['bill_recycle'] = 0;
        $total_bill['bill_rakusatu'] = 0;
        $total_bill['bill_transport_fee'] = 0;
        $total_bill['bill_vanning'] = 0;
        $total_bill['bill_others'] = 0;
        $total_bill['bill_commission'] = 0;
        $total_bill['penalty_amount1'] = 0;
        $total_bill['penalty_amount2'] = 0;

        foreach ($cars as $car) {
            $total_bill['bill_total_amount'] += $car->bill_total_amount;
            $total_bill['bill_price'] += $car->bill_price;
            $total_bill['bill_vat'] += ($car->bill_price*$car->bill_vat)/100;
            $total_bill['bill_recycle'] += $car->bill_recycle;
            $total_bill['bill_rakusatu'] += $car->bill_rakusatu;
            $total_bill['bill_transport_fee'] += $car->bill_transport_fee;
            $total_bill['bill_vanning'] += $car->bill_vanning;
            $total_bill['bill_others'] += $car->bill_others;
            $total_bill['bill_commission'] += $car->bill_commission;
        }

        foreach ($penalties1 as $penalty) {
            $total_bill['penalty_amount1'] += $penalty->penalty_amount;
        }

        foreach ($penalties2 as $penalty) {
            $total_bill['penalty_amount2'] += $penalty->penalty_amount;
        }

        Session::set('total_bill', $total_bill);
        return View::make('nimo.domains.car_balance.Main.bill_create')
            ->with('cars', $cars)
            ->with('customer', $step1_data['customer_id'])
            ->with('total_bill', $total_bill)
            ->with('penalties1', $penalties1)
            ->with('penalties2', $penalties2)
            ;
    }

    /**
     * PurchaseCar create form processing.
     *
     * @return Redirect
     */
    public function postCreate()
    {
        // only admin & customer (hyazgaarlagdmal erhteiger) handana
        $this->checkPermission(array('admin'));

        $step1_data = Session::get('bill_create_step1');
        $total_bill = Session::get('total_bill');
        //var_dump($step1_data['cars']); die;
        $bill = new Bill();
        $bill->create_date = e(Input::get('create_date'));
        $bill->expiry_date = e(Input::get('expiry_date'));
        $bill->customer_id = $step1_data['customer_id'];
        $bill->carry_over_amount = e(Input::get('umnuh_uldegdel'));
        $bill->bill_amount = $total_bill['bill_total_amount'];
        $bill->penalty1_amount = $total_bill['penalty_amount1'];
        $bill->penalty2_amount = $total_bill['penalty_amount2'];
        $bill->total_amount = intval($bill->carry_over_amount) + intval($bill->bill_amount) + intval($bill->penalty1_amount) +  intval($bill->penalty2_amount);

        // Was the purchase_car created?
        if($bill->save())
        {
            if(count($step1_data['cars']) != 0) {
                foreach ($step1_data['cars'] as $id) {
                    $purchase_car = PurchaseCar::find($id);
                    $purchase_car->bill_id = $bill->id;
                    $purchase_car->save();
                }
            }

            if(count($step1_data['penalties1']) != 0) {
                foreach ($step1_data['penalties1'] as $id) {
                    $penalty = Penalty::find($id);
                    $penalty->bill_id = $bill->id;
                    $penalty->save();
                }
            }

            if(count($step1_data['penalties2']) != 0) {
                foreach ($step1_data['penalties2'] as $id) {
                    $penalty = Penalty::find($id);
                    $penalty->bill_id = $bill->id;
                    $penalty->save();
                }
            }
            // Redirect to the new purchase_car page
            //return Redirect::route("car_balance/main/car/")->with('id', $purchase_car->id)->with('success', 'PurchaseCar created successfully');

            Session::forget('bill_car_list.filter');
            Session::forget('bill_create_step1');
            Session::forget('total_bill');

            return Redirect::route('car_balance.bill.detial', array('id' => $bill->id))->with('success', 'Bill created successfully');
        }

        // Redirect to the purchase_car create page
        return Redirect::route('car_balance.bill.create.step2')->with('error', 'Bill was not created, please try again.');

    }

    /**
     * PurchaseCar create form processing.
     *
     * @return Redirect
     */
    public function postTransportOther()
    {
        // only admin & customer (hyazgaarlagdmal erhteiger) handana
        $this->checkPermission(array('admin'));

        $car_id = Request::get('carId');
        $bill_transport = Request::get('bill_transport');
        $bill_others = Request::get('bill_others');

        $purchase_car = PurchaseCar::find($car_id);

        if (!is_null($purchase_car)) {
            $purchase_car->bill_total_amount = $purchase_car->bill_total_amount - $purchase_car->bill_transport_fee - $purchase_car->bill_others;
            $purchase_car->bill_transport_fee = $bill_transport;
            $purchase_car->bill_others = $bill_others;
            $purchase_car->bill_total_amount = $purchase_car->bill_total_amount + $purchase_car->bill_transport_fee + $purchase_car->bill_others;
            $purchase_car->save();
            return Response::json(array('status' => 'ok'));
        }

    }

    /**
     * PurchaseCar update.
     *
     * @param  int  $id
     * @return View
     */
    public function getEdit($id = null)
    {
        // only admin & customer (hyazgaarlagdmal erhteiger) handana
        $this->checkPermission(array('admin'));

        // Check if the purchase_car exists
        if (is_null($bill = Bill::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.bill.index')->with('error', "Bill [$id] does not exist.");
        }

        $purchase_car = new PurchaseCar();
        $purchase_car = $purchase_car->where('bill_id', '=', $bill->id);
        $purchase_car = $purchase_car->orderBy('purchase_date', 'asc');
        $cars = $purchase_car->get();

        $query1 = new Penalty();
        $query1 = $query1->where('bill_id', '=', $bill->id);
        $query1 = $query1->where('penalty_type', '=', '1');
        $query1 = $query1->orderBy('penalty_date', 'asc');

        $penalties1 = $query1->get();

        $query2 = new Penalty();
        $query2 = $query2->where('bill_id', '=', $bill->id);
        $query2 = $query2->where('penalty_type', '=', '2');
        $query2 = $query2->orderBy('penalty_date', 'asc');

        $penalties2 = $query2->get();

        $total_bill = array();
        $total_bill['bill_price'] = 0;
        $total_bill['bill_vat'] = 0;
        $total_bill['bill_recycle'] = 0;
        $total_bill['bill_rakusatu'] = 0;
        $total_bill['bill_transport_fee'] = 0;
        $total_bill['bill_vanning'] = 0;
        $total_bill['bill_others'] = 0;
        $total_bill['bill_commission'] = 0;
        $total_bill['bill_total_amount'] = 0;
        $total_bill['bill_sub_total_amount'][0] = 0;
        $total_bill['penalty_amount1'] = 0;
        $total_bill['penalty_amount2'] = 0;

        foreach ($cars as $key => $car) {
            $total_bill['bill_price'] += $car->bill_price;
            $total_bill['bill_vat'] += ($car->bill_price*$car->bill_vat)/100;
            $total_bill['bill_recycle'] += $car->bill_recycle;
            $total_bill['bill_rakusatu'] += $car->bill_rakusatu;
            $total_bill['bill_transport_fee'] += $car->bill_transport_fee;
            $total_bill['bill_vanning'] += $car->bill_vanning;
            $total_bill['bill_others'] += $car->bill_others;
            $total_bill['bill_commission'] += $car->bill_commission;
            $total_bill['bill_total_amount'] += $car->bill_total_amount;
            if ($key == 0) {
                $total_bill['bill_sub_total_amount'][$key] = $car->bill_total_amount;
            }
            else {
                $total_bill['bill_sub_total_amount'][$key] = $total_bill['bill_sub_total_amount'][$key-1] + $car->bill_total_amount;
            }
        }

        foreach ($penalties1 as $penalty) {
            $total_bill['penalty_amount1'] += $penalty->penalty_amount;
        }

        foreach ($penalties2 as $penalty) {
            $total_bill['penalty_amount2'] += $penalty->penalty_amount;
        }

        Session::set('total_bill', $total_bill);

        return View::make('nimo.domains.car_balance.Main.bill_edit')
            ->with('bill', $bill)
            ->with('cars', $cars)
            ->with('penalties1', $penalties1)
            ->with('penalties2', $penalties2)
            ->with('total_bill', $total_bill)
            ;
    }

    /**
     * PurchaseCar update form processing page.
     *
     * @param  int  $id
     * @return Redirect
     */
    public function postEdit($id = null)
    {
        // only admin & customer (hyazgaarlagdmal erhteiger) handana
        $this->checkPermission(array('admin'));

        $total_bill = Session::get('total_bill');

        // Check if the purchase_car exists
        if (is_null($bill = Bill::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.bill.index')->with('error', "Bill [$id] does not exist.");
        }

        $bill->create_date = e(Input::get('create_date'));
        $bill->expiry_date = e(Input::get('expiry_date'));
        $bill->carry_over_amount = e(Input::get('umnuh_uldegdel'));
        $bill->bill_amount = $total_bill['bill_total_amount'];
        $bill->penalty1_amount = $total_bill['penalty_amount1'];
        $bill->penalty2_amount = $total_bill['penalty_amount2'];
        $bill->total_amount = intval($bill->carry_over_amount) + intval($bill->bill_amount) + intval($bill->penalty1_amount) +  intval($bill->penalty2_amount);

        // Was the purchase_car created?
        if($bill->save())
        {
            Session::forget('total_bill');
            return Redirect::route('car_balance.bill.detial', array('id' => $bill->id))->with('success', 'Bill updated successfully');
        }

        // Redirect to the purchase_car create page
        return Redirect::route('car_balance.bill.edit', array('id' => $bill->id))->with('error', 'Bill was not updated, please try again.');

    }

    public function billDetial($id = null)
    {
        // only admin & customer (hyazgaarlagdmal erhteiger) handana
        $this->checkPermission(array('admin', 'customer'));

        // Check if the purchase_car exists
        if (is_null($bill = Bill::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.bill.index')->with('error', "Bill [$id] does not exist.");
        }

        // only for customer
        if(Sentry::getUser()->hasAccess('customer', false)) {
            // user table-s customer-g herhen tanih we?
            $user = Sentry::getUser();
            $customerQuery = new Customer();
            $customer = $customerQuery->where('id', '=', $user->customer_id)->first();
            if($customer) {
                if($bill->customer_id != $customer->id)
                    App::abort(403, 'Хандах эрх хүрэлцэхгүй байна!');
            } else {
                App::abort(403, 'Хандах эрх хүрэлцэхгүй байна!');
            }
        }

        $purchase_car = new PurchaseCar();
        $purchase_car = $purchase_car->where('bill_id', '=', $bill->id);
        $purchase_car = $purchase_car->orderBy('purchase_date', 'asc');
        $cars = $purchase_car->get();

        $query1 = new Penalty();
        $query1 = $query1->where('bill_id', '=', $bill->id);
        $query1 = $query1->where('penalty_type', '=', '1');
        $query1 = $query1->orderBy('penalty_date', 'asc');

        $penalties1 = $query1->get();

        $query2 = new Penalty();
        $query2 = $query2->where('bill_id', '=', $bill->id);
        $query2 = $query2->where('penalty_type', '=', '2');
        $query2 = $query2->orderBy('penalty_date', 'asc');

        $penalties2 = $query2->get();

        $total_bill = array();
        $total_bill['bill_price'] = 0;
        $total_bill['bill_vat'] = 0;
        $total_bill['bill_recycle'] = 0;
        $total_bill['bill_rakusatu'] = 0;
        $total_bill['bill_transport_fee'] = 0;
        $total_bill['bill_vanning'] = 0;
        $total_bill['bill_others'] = 0;
        $total_bill['bill_commission'] = 0;
        $total_bill['bill_total_amount'] = 0;
        $total_bill['bill_sub_total_amount'][0] = 0;
        $total_bill['penalty_amount1'] = 0;
        $total_bill['penalty_amount2'] = 0;

        foreach ($cars as $key => $car) {
            $total_bill['bill_price'] += $car->bill_price;
            $total_bill['bill_vat'] += ($car->bill_price*$car->bill_vat)/100;
            $total_bill['bill_recycle'] += $car->bill_recycle;
            $total_bill['bill_rakusatu'] += $car->bill_rakusatu;
            $total_bill['bill_transport_fee'] += $car->bill_transport_fee;
            $total_bill['bill_vanning'] += $car->bill_vanning;
            $total_bill['bill_others'] += $car->bill_others;
            $total_bill['bill_commission'] += $car->bill_commission;
            $total_bill['bill_total_amount'] += $car->bill_total_amount;
            if ($key == 0) {
                $total_bill['bill_sub_total_amount'][$key] = $car->bill_total_amount;
            }
            else {
                $total_bill['bill_sub_total_amount'][$key] = $total_bill['bill_sub_total_amount'][$key-1] + $car->bill_total_amount;
            }
        }

        foreach ($penalties1 as $penalty) {
            $total_bill['penalty_amount1'] += $penalty->penalty_amount;
        }

        foreach ($penalties2 as $penalty) {
            $total_bill['penalty_amount2'] += $penalty->penalty_amount;
        }

        return View::make('nimo.domains.car_balance.Main.bill_detial')
            ->with('bill', $bill)
            ->with('cars', $cars)
            ->with('penalties1', $penalties1)
            ->with('penalties2', $penalties2)
            ->with('total_bill', $total_bill)
            ;
    }

}